﻿package _Pan3D.core{
	import _Pan3D.cameras.Camera3D;
	import _Pan3D.base.Object3D
// --------------MSN:lation_pan@live.cn  QQ: 3423526------------- //

	public class calculation {
		


		public static function _get_hit_rec(A,B,C,_Cam:Camera3D,mousex,mousey) {
			var _obj = _PanelEquationFromThreePt(A, B, C);
			var _D = _math_intersect(_obj, _Cam,mousex,mousey) 
			_anti_computing_point(_D, _Cam)
			
			//trace(int(_D.x), int(_D.y), int(_D.z))
			return(_D)
		}
		public static function _math_intersect(_obj,_Cam,mousex,mousey) {
			var a=_obj.a
			var b=_obj.b
			var c=_obj.c
			var d=_obj.d
			
			//mousex=x / (z + _Cam._br) * _Cam._br;    (1)
			//mousey=-y / (z + _Cam._br) * _Cam._br;   (2)
			//ax+by+cz+d=0;                            (3)

			var _D:Object3D=new Object3D()
			_D.rz = ((b * mousey - a * mousex - d) * _Cam._br) / (a * mousex - b * mousey + c * _Cam._br);
			_D.rx = mousex * (b * mousey - a * mousex - d) / (a * mousex - b * mousey + c * _Cam._br) + mousex;
			_D.ry = -(mousey * (b * mousey - a * mousex - d) / (a * mousex - b * mousey + c * _Cam._br) + mousey);
			
			return _D
		}
		public static function _anti_computing_point(_3dpoint:Object3D,_Cam:Camera3D) {

			var rx = _3dpoint.rx;
			var ry = _3dpoint.ry;
			var rz = _3dpoint.rz;
			
			var sin_y = Math.sin(-_Cam.angle_y *  Math.PI / 180);
			var cos_y = Math.cos(-_Cam.angle_y *  Math.PI / 180);
			
			var sin_x = Math.sin(-_Cam.angle_x *  Math.PI / 180);
			var cos_x = Math.cos( -_Cam.angle_x *  Math.PI / 180);
			
			var tmp_ry = ry;
			ry = cos_x * tmp_ry - sin_x * rz;
			rz = sin_x * tmp_ry + cos_x * rz;
			
			var tmp_rx = rx;
			
			rx = cos_y * tmp_rx - sin_y * rz;
			rz = sin_y * tmp_rx + cos_y * rz;
			
			
			_3dpoint.x = int(rx + _Cam.x);
			_3dpoint.y = int(ry + _Cam.y);
			_3dpoint.z = int(rz + _Cam.z);
		}
		public static function _math_change_point(_3dpoint:Object3D,_Cam:Camera3D) {
			var rx = _3dpoint.x -_Cam.x 
			var ry = _3dpoint.y -_Cam.y
			var rz = _3dpoint.z -_Cam.z
	
			var tmp_rx = rx;
		
			rx = _Cam.cos_y * tmp_rx - _Cam.sin_y * rz;
			rz = _Cam.sin_y * tmp_rx + _Cam.cos_y * rz;
			
			var tmp_ry = ry;
			ry = _Cam.cos_x * tmp_ry - _Cam.sin_x * rz;
			rz = _Cam.sin_x * tmp_ry + _Cam.cos_x * rz;
				
			_3dpoint.rx = rx;
			_3dpoint.ry = ry;
			_3dpoint.rz = rz;

		}
		public static function _PanelEquationFromThreePt(p1,p2,p3) {
			var a = ( (p2.y-p1.y)*(p3.z-p1.z)-(p2.z-p1.z)*(p3.y-p1.y) );
		    var b = ( (p2.z-p1.z)*(p3.x-p1.x)-(p2.x-p1.x)*(p3.z-p1.z) );
			var c = ( (p2.x-p1.x)*(p3.y-p1.y)-(p2.y-p1.y)*(p3.x-p1.x) );
		    var d = ( 0 - (a * p1.x + b * p1.y + c * p1.z) );
			return {a:a,b:b,c:c,d:d}
		}
		public static function _DistPt2Panel(p,E) {
			 return  Math.abs(E.a*p.x+E.b*p.y+E.c*p.z+E.d) / Math.sqrt(E.a*E.a+E.b*E.b+E.c*E.c);
		}


	}
}
